# -*- coding:utf-8 -*-
"""
Created on 2009-12-24

@author: madlee
"""

import wx
import wx.xrc as xrc
import os.path
from kuai.pim.database import Database

APP_TITLE = u"快快贴"
RESOURCE_FOLDER = "res"

class MainFrame(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        wx.TextCtrl(self, style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER|wx.TE_RICH2)
        icon = wx.GetApp().res.LoadIcon("ICON_KUAIPIM")
        self.SetIcon(icon)
        
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        
    def OnClose(self, event):
        if event.CanVeto():
            self.Show(False)
        else:
            self.Destroy()


class KuaiPIMTrayIcon(wx.TaskBarIcon):
    def __init__(self, *args, **kwargs):
        wx.TaskBarIcon.__init__(self, *args, **kwargs)
        self.Bind(wx.EVT_TASKBAR_LEFT_DOWN, self.onClick)
        self.Bind(wx.EVT_MENU, self.onClick, id=wx.ID_OPEN)
        self.Bind(wx.EVT_MENU, self.onExit, id=wx.ID_EXIT)
        
    def onClick(self, event):
        frame = wx.GetApp().frame
        if not frame.IsShown():
            frame.Show()
        frame.SetFocus()
            
    def onExit(self, event):
        self.RemoveIcon()
        frame = wx.GetApp().frame
        frame.Destroy()
        self.Destroy()
        
    def CreatePopupMenu(self):
        return wx.GetApp().res.LoadMenu("MENU_ID_TRAY_POP");
    
class KuaiPIMApp(wx.App):
    def __init__(self, database, *args, **kwargs):
        wx.App.__init__(self, *args, **kwargs)
        self.db = Database(database)
        
    def OnInit(self):
        global RESOURCE_FOLDER
        if os.path.isdir(RESOURCE_FOLDER):
            self.res = xrc.XmlResource(os.path.join(RESOURCE_FOLDER, "kuaipim.xrc"))
        else:
            RESOURCE_FOLDER = "kuaipim.zip#zip:res"
            wx.FileSystem_AddHandler(wx.ZipFSHandler())
            self.res = xrc.XmlResource(os.path.join(RESOURCE_FOLDER, "kuaipim.xrc"))
            
        self.frame = MainFrame(None, wx.ID_ANY, APP_TITLE)
        self.icon = KuaiPIMTrayIcon()
        self.icon.SetIcon(self.frame.GetIcon(), APP_TITLE)
        self.frame.Show()
        return True
    
    def OnExit(self):
        print "I'm quiting!"
    
if __name__ == '__main__':
    database = "kuaipim.db"
    from sys import argv
    if len(argv) == 2:
        database = argv[1]
    
    app = KuaiPIMApp(database, False)
    app.MainLoop()
